﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Haozes.FxClient;
using Haozes.FxClient.Core;
using System.Threading;
using FetionWebMessenger.AddWebService;
namespace FetionWebMessenger
{
    public class FetionCore
    {
        private Client fetion;
        //消息池,最大消息数为10
        private String[] MessengerPool = new String[10];
        //当前状态
        private String StatePool;
        public bool StateFlash = false;
        private String SystemMSG;
        private String ContactsXML = "";
        private String MessageXML = "";
        private String SysMsgXML = "";
        //消息计数
        private int MessengerCounter = -1;
        //重试次数
        private int retryCount = 5;
        //有系统消息的标记
        public bool sysMSG = false;
        //添加好友的消息请求
        public static event EventHandler ContactsChanged;
        public String systemMSG
        {
            get
            {
                sysMSG = false;
                return SystemMSG;
            }
            set
            {
                sysMSG = true;
                SystemMSG = value;
            }
        }
        public String Uri
        {
            get
            {
                return fetion.CurrentUser.Uri.ToString();
            }
        }
        //获取当前的消息计数
        public int messengerCounter
        {
            get { return MessengerCounter; }
        }
        //当前的状态池
        public String statePool
        {
            get
            {
                StateFlash = false;
                return StatePool;
            }
            set
            {
                StateFlash = true;
                StatePool = value;
            }
        }
        //登入
        public void LoginFetion()
        {
            //这里写守护进程的用户.
           // LoginFetion("", "");
        }
        //登入
        public void LoginFetion(string mobile, string pwd)
        {
            //调用登陆
            //初始化飞信
            InitFx();
            statePool = "登录中";
            fetion.Login(mobile, pwd);
        }
        //获取个人的信息
        public String GetMyInfo()
        {
            String tmp = "<MeInfo><MobileNo>" + fetion.CurrentUser.MobileNo + "</MobileNo>";
            tmp += "<Name>" + fetion.CurrentUser.Name + "</Name>";
            tmp += "<NickName>" + fetion.CurrentUser.NickName + "</NickName>";
            tmp += "<Uri>" + fetion.CurrentUser.Uri.Raw + "</Uri></MeInfo>";
            return tmp;
        }
        //登出
        public void LogoutFetion()
        {
            //登出
            StatePool = "登出中";
            fetion.Exit();
            fetion.LoginSucceed -= new EventHandler(fetion_LoginSucceed);
            fetion.LoginFailed -= new EventHandler(fetion_LoginFailed);
            fetion.Errored -= new EventHandler<Haozes.FxClient.Core.FxErrArgs>(fetion_Errored);
            fetion.MsgReceived -= new EventHandler<Haozes.FxClient.Core.ConversationArgs>(fetion_OnMsgReceived);
            fetion.Deregistered -= new EventHandler(fetion_OnDeregistered);
            fetion.AddBuddyRequest -= new EventHandler<ConversationArgs>(fetion_AddBuddyRequest);
            fetion.AddBuddyResult -= new EventHandler<ConversationArgs>(fetion_AddBuddyResult);
            fetion.DeleteBuddyResult -= new EventHandler<ConversationArgs>(fetion_DeleteBuddyResult);
            statePool = "已退出";
        }
        //发送给某人_to_Fetion
        public Boolean SendMsgTo(string uri, string MSG)
        {
            SipUri sipUri = FindUri(uri);
            if (sipUri == null)
            {
                return false;
            }
            fetion.SendMsg(sipUri, MSG);
            return true;
        }
        //发送给某人_to_手机
        public Boolean SendSMSTo(string uri, string MSG)
        {
            SipUri sipUri = FindUri(uri);
            if (sipUri == null)
            {
                return false;
            }
            fetion.SendSMS(sipUri, MSG);
            return true;
        }
        //发给自己手机
        public Boolean SendToSelf(String content)
        {
            fetion.SendToSelf(content);
            return true;
        }
        //添加好友
        public void AddBuddy(String mobile, String NickName)
        {
            mobile = string.Format("tel:{0}", mobile);
            SipUri Uri = new SipUri(mobile);
            string str= string.Format("{0}请求加你为飞信好友", fetion.CurrentUser.NickName);
            fetion.AddBuddy(Uri, str);
            statePool = "添加好友中";
        }
        //删除好友
        public void DeleteBuddy(String mobile)
        {
            fetion.DeleteBuddy(new SipUri(mobile));
            statePool = "删除好友中";
        }
        //同意添加该好友为好友
        public void AgreeAddBuddy(String mobile)
        {
            fetion.AgreeAddBuddy(new SipUri(mobile));
        }
        //获取消息
        public String PeekMessage()
        {
            String tmp = "<Messages>";
            tmp += MessageXML;
            tmp += "</Messages>";
            MessageXML = "";
            return tmp;
        }
        //获取系统消息
        public String PeekSysMessage()
        {
            String tmp = "<msgcontent>";
            tmp += SysMsgXML;
            tmp += "</msgcontent>";
            return tmp;
        }
        //获取好友列表
        public String GetFriendsList()
        {
            String tmp = "<msgcontent>";
            tmp += ContactsXML;
            tmp += "</msgcontent>";
            return tmp;
        }
        //查找URI
        private SipUri FindUri(String uri)
        {
            IList<Contact> list = fetion.CurrentUser.Contacts;
            foreach (Contact contact in list)
            {
                if (contact.Uri.ToString().Equals(uri))
                {
                    return contact.Uri;
                }
            }
            return null;
        }
        //初始化飞信调用
        private void InitFx()
        {
            fetion = new Client();
            // fetion.Log = LogUtil.Log;
            fetion.LoginSucceed += new EventHandler(fetion_LoginSucceed);
            fetion.LoginFailed += new EventHandler(fetion_LoginFailed);
            fetion.Load += new EventHandler(fetion_Load);
            fetion.Errored += new EventHandler<Haozes.FxClient.Core.FxErrArgs>(fetion_Errored);
            fetion.MsgReceived += new EventHandler<Haozes.FxClient.Core.ConversationArgs>(fetion_OnMsgReceived);
            fetion.Deregistered += new EventHandler(fetion_OnDeregistered);
            fetion.AddBuddyRequest += new EventHandler<ConversationArgs>(fetion_AddBuddyRequest);
            fetion.AddBuddyResult += new EventHandler<ConversationArgs>(fetion_AddBuddyResult);
            fetion.DeleteBuddyResult += new EventHandler<ConversationArgs>(fetion_DeleteBuddyResult);
        }
        //删除好友的回调
        private void fetion_DeleteBuddyResult(object sender, ConversationArgs e)
        {
            if (e.Text == "200")
            {
                statePool = "删除好友成功";
            }
        }
        //添加好友的回调
        private void fetion_AddBuddyResult(object sender, ConversationArgs e)
        {
            string result = e.Text;
            if (!string.IsNullOrEmpty(result))
            {
                statePool = "添加好友成功";
            }
            else
            {
                statePool = "添加好友失败";
            }
        }
        //请求添加为好友的请求
        private void fetion_AddBuddyRequest(object sender, ConversationArgs e)
        {
            SysMsgXML += "<AddBuddyRequest>" + e.Text + "</AddBuddyRequest>";
            //systemMSG = e.Text;
        }
        //其它客户端登陆信息
        private void fetion_OnDeregistered(object sender, EventArgs e)
        {
            LogoutFetion();
            statePool = "用户已从其他客户端登陆,系统退出";
        }
        //登陆失败的回调
        private void fetion_LoginFailed(object sender, EventArgs e)
        {
            ReLogin();
            statePool = "登录失败";
        }
        //登陆成功
        private void fetion_LoginSucceed(object sender, EventArgs e)
        {
            statePool = "登陆成功";
            retryCount = 5;
        }
        //获取联系人列表
        private void fetion_Load(object sender, EventArgs e)
        {
            fetion.CurrentUser.ContactsManager.ContactsChanged += new EventHandler<ContactsChangedArg>(ContactsManager_ContactsChanged);
            IList<Contact> list = fetion.CurrentUser.Contacts;
            foreach (Contact con in list)
            {
                //需要除去黑名单中的
                if (-9223372036854775808 != con.MobileNo)
                {
                    ContactsXML += "<buddy>";
                    ContactsXML += "<DisplayName>" + con.DisplayName + "</DisplayName>";
                    ContactsXML += "<Uri>" + con.Uri + "</Uri>";
                    ContactsXML += "<NickName>" + con.NickName + "</NickName>";
                    ContactsXML += "<MobileNo>" + con.MobileNo + "</MobileNo>";
                    ContactsXML += "<Impresa>" + con.Impresa + "</Impresa>";
                    ContactsXML += "</buddy>";
                }
            }
        }
        private static void ContactsManager_ContactsChanged(object sender, ContactsChangedArg e)
        {
            if (ContactsChanged != null)
            {
                ContactsChanged(null, e);
            }
        }
        //收到消息
        private void fetion_OnMsgReceived(object sender, Haozes.FxClient.Core.ConversationArgs e)
        {
            if (sender != null)
            {
                Conversation conv = (Conversation)sender;
                if (e.MsgType == IMType.Text || e.MsgType == IMType.SMS)
                {
                    //获取到消息还需要处理,这里暂时这样吧
                    MessageXML += "<Message><Uri>" + e.RawPacket.From.Value + "</Uri>";
                    MessageXML += "<Time>";
                    DateTime time = DateTime.Parse(e.RawPacket.Date.Value);
                    MessageXML += time.ToString("yyyy-MM-dd HH:mm:ss");
                    MessageXML += "</Time>";
                    MessageXML += "<Content>" + e.Text + "</Content></Message>";
                }
            }
        }
        //发生错误
        private void fetion_Errored(object sender, Haozes.FxClient.Core.FxErrArgs e)
        {
            --retryCount;
            if (retryCount > 0)
            {
                if (e.Level == ErrLevel.Fatal)
                {
                    ReLogin();
                    statePool = "重新登录中登陆";
                }
            }
            else
            {
                statePool = "登陆失败";
            }
        }
        //重新登陆
        private void ReLogin()
        {
            LogoutFetion();
            Thread.Sleep(200);
            LoginFetion();
        }
        //构造消息的XML
        private String FormatMSGXML()
        {
            return "";
        }

    }
}
